package com.example.home.mvvm.activity

import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.home.R
import com.example.home.mvvm.fragment.HomeFragment
import com.example.home.mvvm.viewmodel.HomeViewModel
import com.example.home.mvvm.weights.TabItemsView
import com.google.android.material.tabs.TabLayout
import com.gsafety.libraryktx.adapter.CommonVPAdapter
import com.gsafety.libraryktx.base.BaseActivity
import com.gsafety.libraryktx.base.BaseFragment
import com.gsafety.libraryktx.bean.LoadState
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.core.RouterConstants
import com.gsafety.libraryktx.expand.create
import com.gsafety.libraryktx.expand.toast
import com.gsafety.libraryktx.manager.UserManager
import com.gsafety.libraryktx.util.StatusUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.home_activity_main.*
import kotlinx.android.synthetic.main.home_fragment_layout.*
import kotlin.system.exitProcess

/**
 * @author : lj
 * @date : 2020/10/12 15:02
 */
@Route(path = RouterConstants.MAIN_ACTIVITY)
class MainActivity: BaseActivity() {
    private lateinit var mv: HomeViewModel
    private var homeVPAdapter:CommonVPAdapter? = null
    private var msgTabIndex = 0
    private var alarmTabIndex = 0
    private var knowTabIndex = 0
    override fun initView() {
        initmodel()
        msgTabIndex = 0
        tab_layout.setupWithViewPager(view_pager)
        var codes=UserManager.getInstance().appModelCodes()
        var tabTitleArray=ArrayList<String>()
        var fragments = ArrayList<Fragment>()
        codes?.also {
            if(it.contains(Constant.CODE_HOME_PAGE)) {
                fragments.add(HomeFragment())
                tabTitleArray.add(resources.getString(R.string.home_tab))
                ++msgTabIndex
                ++alarmTabIndex
                ++knowTabIndex
            }
            if(it.contains(Constant.CODE_YJ_PAGE)){
                fragments.add(ARouter.getInstance().build(RouterConstants.ALARM_FRAGMENT).navigation() as BaseFragment)
                tabTitleArray.add(resources.getString(R.string.home_alarm_tab))
                ++msgTabIndex
                ++knowTabIndex
            }
            if(it.contains(Constant.CODE_MESSAGE_PAGE)){
                fragments.add(ARouter.getInstance().build(RouterConstants.MESSAGE_FRAGMENT).navigation() as BaseFragment)
                tabTitleArray.add(resources.getString(R.string.home_message_tab))
                ++knowTabIndex
            }
            if(it.contains(Constant.CODE_KNOWLEDGE_PAGE)){
                fragments.add(ARouter.getInstance().build(RouterConstants.KNOW_FRAGMENT).navigation() as BaseFragment)
                tabTitleArray.add(resources.getString(R.string.home_knowledge_tab))
            }
            if(it.contains(Constant.CODE_MY_PAGE)){
                fragments.add(ARouter.getInstance().build(RouterConstants.PERSONAL_FRAGMENT).navigation() as BaseFragment)
                tabTitleArray.add(resources.getString(R.string.home_me_tab))
            }
            homeVPAdapter = CommonVPAdapter(supportFragmentManager)
            homeVPAdapter?.setFragments(fragments)
            view_pager.adapter = homeVPAdapter
            for (i in tabTitleArray.indices) {
                val tab: TabLayout.Tab = tab_layout.getTabAt(i)!!
                val tiv = TabItemsView(this, i)
                tiv.findViewById<TextView>(R.id.tv_num)?.visibility = View.GONE

                tab.customView = tiv
            }
        }

        LiveEventBus.get(Constant.EventBus_KEY_Message_Num,String::class.java).observe(
            this,
            Observer { it ->
                var numView =
                    tab_layout.getTabAt(msgTabIndex)?.view?.findViewById<TextView>(R.id.tv_num)
                numView?.text = it
                if(it.length >= 4){
                    numView?.textSize = 6f
                }
                if(it == "0"){
                    numView?.visibility = View.GONE
                }else{
                    numView?.visibility = View.VISIBLE
                }
            })

        LiveEventBus.get(Constant.EventBus_KEY_Alarm_Deal_Click,String::class.java).observe(
            this,
            Observer { it ->
                switchTab(it)
            })
        LiveEventBus.get(Constant.EventBus_KEY_Know_Switch,String::class.java).observe(
            this,
            Observer { it ->
                if(it == "know") {
                    tab_layout.getTabAt(knowTabIndex)?.select()
                }
            })
        LiveEventBus.get(Constant.EventBus_KEY_LOGINOUT,String::class.java).observe(
            this,
            Observer { it ->
                mv.logout()
                ARouter.getInstance().build(RouterConstants.LOGIN_ACTIVITY).navigation()
                UserManager.getInstance().removeLogin()
                finish()
            })
    }

    fun switchTab(index:String){
        tab_layout.getTabAt(alarmTabIndex)?.select()
        LiveEventBus.get(Constant.EventBus_KEY_Alarm_Deal_Switch).post(index)
    }

    override fun initData() {

    }

    override fun getLayoutId(): Int {
        return R.layout.home_activity_main
    }

    override fun statusBar() {
        StatusUtils.transparentStatusBar(this)
    }

    override fun onResume() {
        super.onResume()
        mv.requesthome()
    }

    private fun initmodel(){
        mv = HomeViewModel()
        mv = create(HomeViewModel::class)
        mv.loadState.observe(this, Observer {
            when (it) {
                is LoadState.Success -> {
                    var data=mv.data.value
                    data?.also {
                        LiveEventBus.get(Constant.EventBus_KEY_Message_Num).post(data.unread)
                    }
                }
                is LoadState.Fail -> {
                }

            }
        })
    }
    private var firstTime: Long = 0
    override fun handBack(): Boolean {
        val secondTime = System.currentTimeMillis()
        // 如果两次按键时间间隔大于2000毫秒，则不退出
        if (secondTime - firstTime > 2000) {
            toast("再按一次退出应用")
            firstTime = secondTime// 更新firstTime
            return true
        } else {
            exit()
        }
        return false
    }

    private fun exit() {
        finish()
        //退出程序
        android.os.Process.killProcess(android.os.Process.myPid())
        exitProcess(0)
    }
}